//
//  LCRecommendViewController.m
//  TianXiaShi
//
//  Created by qianfeng01 on 15-7-11.
//  Copyright (c) 2015年 CongCong. All rights reserved.
//

#import "LCRecommendViewController.h"
#import "LCDetailViewController.h"
#import "LCSubjectViewController.h"
@interface LCRecommendViewController ()

@end

@implementation LCRecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.postionId = @"0";
    [self creatCollectionView];
}
- (void)downWebDataWithUrl:(NSString *)url
{
    //[NSString stringWithFormat:@"%@%@%@%@",recommend1,self.channelId,recommend2,self.postionId]
    //NSLog(@"%@",url);
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleDrop];
    //[MMProgressHUD showDeterminateProgressWithTitle:@"下载。。。" status:nil];
    [MMProgressHUD showWithStatus:@"下载。。。"];
    __weak typeof(self) weakSelf = self;
    
    [self.manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            [weakSelf initJosnModelWith:dict];
            [MMProgressHUD dismiss];
            [weakSelf.collectionView headerEndRefreshingWithResult:JHRefreshResultSuccess];
            [weakSelf.collectionView footerEndRefreshing];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
         [MMProgressHUD dismissWithError:@"下载失败"];
    }];
    
    
}
- (void)setRefresh
{
    __weak typeof(self) weakSelf = self;
    [self.collectionView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        NSLog(@"刷新");
        //weakSelf.postionId = @"0";
        [weakSelf downWebDataWithUrl:[NSString stringWithFormat:@"%@%@%@%@",recommend1,weakSelf.channelId,recommend2,weakSelf.postionId]];
    }];
    [self.collectionView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        ///NSLog(@"加载跟多");
        LCBodayModel *model = [weakSelf.recommentModel.bodyList lastObject];
        weakSelf.postionId = [model.itemIdList firstObject];
        [weakSelf downWebDataWithUrl:[NSString stringWithFormat:@"%@%@%@%@",recommend1,weakSelf.channelId,recommend2,weakSelf.postionId]];
    }];
    
}
- (void)initJosnModelWith:(NSDictionary *)dict
{
    if ([self.postionId isEqualToString:@"0"]) {
        self.recommentModel = [[LCRecommendModel alloc]initWithDictionary:dict error:nil];
        
    }
    else
    {
        LCRecommendModel *model = [[LCRecommendModel alloc]initWithDictionary:dict error:nil];
        [self.recommentModel.bodyList addObjectsFromArray:model.bodyList];
        
    }
    [self.collectionView reloadData];
}
- (void)creatCollectionView
{
    // 1. 布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // flowLayout.itemSize ...
    // flowLayout.sectionInset = ...
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    // 2. 新建collectionView，并关联布局对象
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-kScreenSize.height/662*154) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.collectionView.frame];
    //背景图片
    imageView.image = [UIImage imageNamed:@"bgView"];
    _collectionView.backgroundView = imageView;
    [self.view addSubview:_collectionView];
    
    // 3. 注册(cell, header, footer)
    [_collectionView registerNib:[UINib nibWithNibName:@"RecommendCell" bundle:nil] forCellWithReuseIdentifier:@"RecommendCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
}
#pragma mark - <UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource>


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.recommentModel.bodyList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LCBodayModel *bodyModel = self.recommentModel.bodyList[indexPath.row];
    LCVideoModel *model = bodyModel.videoList[0];
    RecommendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RecommendCell" forIndexPath:indexPath];

    [cell showModel:model];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(kScreenSize.width/2-15, kScreenSize.height/662*184);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    LCBodayModel *bodyModel = self.recommentModel.bodyList[indexPath.row];
    LCVideoModel *videoModel = bodyModel.videoList[0];
    if ([videoModel.memberType isEqualToString:@"video"]) {
        LCDetailViewController *detail = [[LCDetailViewController alloc]init];
        detail.guid = videoModel.memberItem.guid;
        //NSLog(@"%@",detail.guid);
        
        //[self.navigationController pushViewController:detail animated:YES];
        [self presentViewController:detail animated:YES completion:nil];
    }
    else
    {
        LCSubjectViewController *subject = [[LCSubjectViewController alloc]init];
        subject.memberID = bodyModel.memberIds;
        subject.membertype = videoModel.memberType;
        //[self.navigationController pushViewController:self animated:YES];
         [self presentViewController:subject animated:YES completion:nil];
    }
    
    
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *header;
    if([kind isEqual:UICollectionElementKindSectionHeader])
    {
        header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Header" forIndexPath:indexPath];
        self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height/662*200)];
        self.scroll.contentSize = CGSizeMake(kScreenSize.width*self.recommentModel.header.count, 0);
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
        [self.scroll addGestureRecognizer:tap];
        for (int i=0; i<self.recommentModel.header.count; i++) {
            LCHeaderModel *headerModel = self.recommentModel.header[i];
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenSize.width*i, 0, kScreenSize.width, kScreenSize.height/662*198)];
            
            [image sd_setImageWithURL:[NSURL URLWithString:headerModel.image] placeholderImage:[UIImage imageNamed:@"tupianbg"]];
            
            [self.scroll addSubview:image];
        }
        self.scroll.pagingEnabled = YES;
        self.scroll.bounces = NO;
        self.scroll.showsHorizontalScrollIndicator = NO;
        self.scroll.delegate = self;
        [header addSubview:self.scroll];
        self.pageView = [[UIPageControl alloc]initWithFrame:CGRectMake(kScreenSize.width-80, 180, 80, 20)];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 180, kScreenSize.width, 20)];
        view.backgroundColor = [UIColor grayColor];
        view.alpha = 0.2;
        [header addSubview:view];
        self.pageView.numberOfPages = self.recommentModel.header.count;
        self.pageView.currentPage = 0;
        self.headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 180, kScreenSize.width, 20)];
        LCHeaderModel *headerModel = self.recommentModel.header[0];
        self.headerLabel.text = headerModel.title;
        self.headerLabel.textColor = [UIColor whiteColor];
        [header addSubview:self.headerLabel];
        [header addSubview:self.pageView];
        if (_timer == nil) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
    }
    }
    return header;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {

    return CGSizeMake(kScreenSize.width, kScreenSize.height/662*200);
}

- (void)tap
{
    
    int i = _scroll.contentOffset.x/kScreenSize.width;
    LCHeaderModel  *headerModel = self.recommentModel.header[i];
    if ([headerModel.memberType isEqualToString:@"video"]) {
        LCDetailViewController *detail = [[LCDetailViewController alloc]init];
        detail.guid = headerModel.memberItem.guid;
        //NSLog(@"%@",detail.guid);
        
        //[self.navigationController pushViewController:detail animated:YES];
        [self presentViewController:detail animated:YES completion:nil];
    }
    else
    {
        LCSubjectViewController *subject = [[LCSubjectViewController alloc]init];
        subject.memberID = headerModel.memberId;
        subject.membertype = headerModel.memberType;
        //[self.navigationController pushViewController:self animated:YES];
        [self presentViewController:subject animated:YES completion:nil];
    }

    
}
- (void)changeTimeAtTimedisplay
{
    CGPoint p;
    if (_scroll.contentOffset.x==kScreenSize.width*(self.recommentModel.header.count-1)) {
        p = CGPointMake(0, 0);
    }
    else
    {
        p = CGPointMake(_scroll.contentOffset.x+kScreenSize.width, 0);
    }
    [UIView animateWithDuration:1 animations:^{
        _scroll.contentOffset = p;
    }];
    
    int i = _scroll.contentOffset.x/kScreenSize.width;
    LCHeaderModel *headerModel = self.recommentModel.header[i];
    self.headerLabel.text = headerModel.title;
    self.pageView.currentPage = i;
}




@end
